package com.dyzx.hbb.modules.wms.controller;


import cn.hutool.core.bean.BeanUtil;
import com.dyzx.hbb.common.base.Result;
import com.dyzx.hbb.common.config.MyLambdaQueryWrapper;
import com.dyzx.hbb.common.controller.BaseValidController;
import com.dyzx.hbb.common.utils.Utils;
import com.dyzx.hbb.modules.fcxs.entity.FcxsCustomer;
import com.dyzx.hbb.modules.wms.entity.WmsHouse;

import com.dyzx.hbb.modules.wms.entity.WmsInventory;
import com.dyzx.hbb.modules.wms.entity.WmsProductCategory;
import com.dyzx.hbb.modules.wms.query.WmsHouseQuery;
import com.dyzx.hbb.modules.wms.service.WmsHouseService;
import com.dyzx.hbb.modules.wms.service.WmsInventoryService;
import com.dyzx.hbb.modules.wms.service.WmsProductCategoryService;
import com.dyzx.hbb.modules.wms.vo.WmsHouseVO;
import com.dyzx.hbb.modules.wms.vo.WmsHouseUVO;
import com.dyzx.hbb.security.context.SecurityContextHolder;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

/**
 * 仓库管理控制器
 * <p>处理仓库管理系统中仓库的创建、查询和管理业务逻辑
 * <p>主要职责：
 * <ul>
 * <li>提供仓库的基础CRUD操作</li>
 * <li>支持按名称、类型、状态、编号等条件筛选仓库信息</li>
 * <li>计算并展示仓库内商品的总价值和总数量</li>
 * <li>提供仓库的简易列表接口</li>
 * <li>支持按仓库查询商品类别分布信息</li>
 * <li>自动生成仓库编号</li>
 * </ul>
 * <p>设计意图：为仓库管理模块提供统一的仓库数据管理接口，
 * 确保仓库信息的完整性和可追踪性，支持库存统计分析
 * 
 * @author 开发团队
 * @version 1.0.0
 * @since 2023-05-30
 */
@Tag(name = "仓库管理", description = "仓库相关接口")
@RestController
@RequestMapping("/wms/house")
public class WmsHouseController extends BaseValidController<
        WmsHouseService,
        WmsHouse,
        WmsHouseQuery,
        WmsHouseVO,
        WmsHouseUVO
        > {

    @Autowired
    private WmsHouseService service;
    @Autowired
    private WmsInventoryService inventoryService;

    @Autowired
    private WmsProductCategoryService  productCategoryService;

    @Override
    protected WmsHouseService getBaseService() {
        return service;
    }

    @Override
    protected MyLambdaQueryWrapper<WmsHouse> queryWrapper(WmsHouseQuery query) {
        Long organId = SecurityContextHolder.getOrganId();
        MyLambdaQueryWrapper<WmsHouse> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.select(WmsHouse::getId)
                .select(WmsHouse::getNo)
                .select(WmsHouse::getName)
                .select(WmsHouse::getType)
                .userName(WmsHouse::getLeaderId).as("leader_name")
                .select(WmsHouse::getDescription)
              //  .select("IFNULL((SELECT (SUM(quantity)*(IFNULL((SELECT amt FROM wms_product where id=wms_inventory.product_id LIMIT 1),0))) FROM wms_inventory WHERE house_id=wms_house.id LIMIT 1),0)").as("price")
                .select("IFNULL((SELECT SUM(price*quantity) FROM wms_inventory where  organ_id="+organId+" and house_id=wms_house.id and quantity>0 ),0)").as("price")
                .select("(SELECT SUM((quantity)) FROM wms_inventory where house_id=wms_house.id and quantity>0)").as("quantity")
                .select(WmsHouse::getArea);
        queryWrapper.orderByDesc(WmsHouse::getCreateDate);

        if (query != null) {
            queryWrapper.likeRight(query.getName() != null, WmsHouse::getName, query.getName())
                    .eq(query.getType() != null, WmsHouse::getType, query.getType())
                    .eq(query.getStatus() != null, WmsHouse::getStatus, query.getStatus())
                    .eq(query.getNo() != null, WmsHouse::getNo, query.getNo());
        }
        return queryWrapper;
    }

    @Override
    protected MyLambdaQueryWrapper<WmsHouse> queryInfoWrapper() {
        Long organId = SecurityContextHolder.getOrganId();
        MyLambdaQueryWrapper<WmsHouse> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.select(WmsHouse::getId)
                .select(WmsHouse::getNo)
                .select(WmsHouse::getName)
                .select(WmsHouse::getType)
                .userName(WmsHouse::getLeaderId).as("leader_name")
                .select(WmsHouse::getDescription)
                .select("IFNULL((SELECT SUM(price*quantity) FROM wms_inventory where  organ_id="+organId+" and house_id=wms_house.id and quantity>0 ),0)").as("price")
                .select(WmsHouse::getArea);
        queryWrapper.orderByDesc(WmsHouse::getCreateDate);
        return queryWrapper;
    }

    @Override
    protected WmsHouse addValid(WmsHouseVO entity) {
        Long organId = SecurityContextHolder.getOrganId();
        MyLambdaQueryWrapper<WmsHouse> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.eq(WmsHouse::getOrganId, organId);
        long count = service.count(queryWrapper);
        String no = Utils.generateYMOrderNumber("WH", count);

        WmsHouse wmsHouse = new WmsHouse();
        BeanUtil.copyProperties(entity, wmsHouse);
        wmsHouse.setNo(no);

        return wmsHouse;
    }

    @Override
    protected WmsHouse editValid(WmsHouseUVO entity) {
        return null;
    }

    @Operation(summary = "简易列表")
    @GetMapping("/mini_list")
    public Result<List<Map<String, Object>>> miniList(
    ) {
        Long organId = SecurityContextHolder.getOrganId();
        MyLambdaQueryWrapper<WmsHouse> wrapper = new MyLambdaQueryWrapper<>();
        wrapper.select(WmsHouse::getId, WmsHouse::getName);
        wrapper.select(WmsHouse::getName).as("label");
        wrapper.select(WmsHouse::getId).as("value");
        wrapper.orderByDesc(WmsHouse::getId);
        wrapper.eq(WmsHouse::getOrganId, organId);


        List<Map<String, Object>> list = getBaseService().listMaps(wrapper);
        return list.isEmpty() ? Result.error(404, "暂无数据") : Result.ok(list);
    }
    // 仓库项目:类别 表示产品类别 (如：制动系统，发动机保养，电气部件)
    @Operation(summary = "仓库项目:类别")
    @GetMapping("/category_list/{houseId}")
    public Result<List<Map<String, Object>>> categoryList(
            @PathVariable("houseId") Long houseId
    ) {
        Long organId = SecurityContextHolder.getOrganId();
/*        (SELECT SUM(amt) FROM wms_product WHERE category_id = wms_product_category.id  LIMIT 1),
        (SELECT COUNT(quantity) FROM wms_inventory where product_id = wms_product.id LIMIT 1)*/
        String eQouerySql = "IFNULL((SELECT SUM((quantity)) FROM wms_inventory where organ_id="+organId+" and house_id="+houseId+" and quantity>0  ),0)";
        String realQuantitySql="IFNULL((SELECT SUM(quantity) FROM wms_inventory where organ_id="+organId+" and house_id="+houseId+" and quantity>0 and  product_id in(SELECT id FROM wms_product WHERE category_id = wms_product_category.id) LIMIT 1),0)";
        MyLambdaQueryWrapper<WmsProductCategory> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.select(WmsProductCategory::getId,WmsProductCategory::getName)

               // .select(WmsHouse::getDescription)
               // .select("IFNULL(("+getPriductEsqlAppley(houseId)+"*"+realQuantitySql+"),0)").as("price")
                .select("IFNULL(("+getPriductEsqlAppley(houseId)+"),0)").as("price")
                .select("(("+realQuantitySql+"/"+eQouerySql+")*100)").as("persent")
                .select(realQuantitySql).as("quantity");
       // queryWrapper.eq(WmsInventory::getHouseId, houseId);
        queryWrapper.inSql(WmsProductCategory::getId, getPriductEsql(houseId,"category_id"));
      //  queryWrapper.eq(WmsProductCategory::getOrganId, organId);



     List<Map<String, Object>> list = productCategoryService.listMaps(queryWrapper);
        return list.isEmpty() ? Result.error(404, "暂无数据") : Result.ok(list);
    }
    private  String getPriductEsql( Long houseId,String feild){
        Long organId = SecurityContextHolder.getOrganId();
        return "(SELECT "+feild+" FROM wms_product where id in(SELECT product_id FROM wms_inventory where house_id="+houseId+" and organ_id="+organId+"))";
    }

    private  String getPriductEsqlAppley( Long houseId){
        Long organId = SecurityContextHolder.getOrganId();
        //wms_product_task  产品任务表
      //  return "(SELECT amt_old FROM wms_product_task where product_id in "+s+")";
      //  String cout="IFNULL((SELECT SUM(quantity*price) FROM wms_inventory where house_id="+houseId+" and organ_id="+organId+" and product_id=wms_product.id),0)";
       // return "(SELECT "+cout+" FROM wms_product where category_id=wms_product_category.id and id in(SELECT product_id FROM wms_inventory where house_id="+houseId+" and organ_id="+organId+"))";
        return "IFNULL((SELECT SUM(quantity*price) FROM wms_inventory where house_id="+houseId+" and organ_id="+organId+" and product_id in(SELECT id FROM wms_product WHERE category_id = wms_product_category.id)),0)";
    }
}